import {defineStore} from "pinia";

export const useUsersStore=defineStore('user',{
    //使用容器中state
    state:()=>{
        return{
            username:null,
        };
    },
    //使用容器中的actions 同步和异步请求
    actions:{

    },
    //通过getter 修改state 
    getters:{
        saveUserCode(state){
            if(state.username){
                return state.username
            }else{
                if(localStorage.getItem('username')){
                    return JSON.parse(localStorage.getItem('username')||'{}')
                }
            }
        }
    },
})
const instance = useUsersStore();
instance.$subscribe((_, state) => {
    localStorage.setItem('username', JSON.stringify({ ...state }));
});
// 2. 获取保存的数据，先判断有无，无则用先前的
const username = localStorage.getItem('username');
if (username) {
    instance.$state = JSON.parse(username);
}

